package com.coollang.smartbra.fragment;

import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.coollang.smartbra.R;
import com.coollang.smartbra.activity.ActionActivity;
import com.coollang.smartbra.base.ActionFragment;
import com.coollang.smartbra.base.MyApplication;
import com.coollang.smartbra.beans.ActionData;
import com.coollang.smartbra.utils.ActivitySwitcher;
import com.coollang.smartbra.utils.UIUtils;
import com.coollang.smartbra.views.CircularSeekBarBcg;
import com.coollang.smartbra.views.CountView;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

import static com.coollang.smartbra.R.id.tv_action_details;

/**
 * @author: Timmy
 * @Data: 2017/5/12
 * @Fuction: 计数的Fragment
 */
public class ActionCountFragment extends ActionFragment {
    private static final String TAG = ActionCountFragment.class.getSimpleName();
    @BindView(R.id.tv_next)
    TextView mTvNext;
    @BindView(R.id.btn_start)
    Button mBtnStart;
    @BindView(R.id.circle_seekbar)
    CircularSeekBarBcg mCircularSeekBar;
    @BindView(R.id.nub_stop)
    TextView nubStop;
    @BindView(R.id.tv_lock)
    TextView tvLock;
    @BindView(R.id.tv_current_nub)
    TextView tvCurrentNub;
    @BindView(R.id.tv_heart_rate)
    CountView tvHeartRate;
    @BindView(R.id.tv_u_money)
    CountView tvUMoney;
    @BindView(R.id.pb_progressbar)
    ProgressBar mProgressBar;
    @BindView(R.id.tv_action_count_title)
    TextView mTvActionCountTile;
    @BindView(R.id.action_corrent_count)
    TextView mTvActionCorrentTile;
    @BindView(R.id.action_error_count)
    TextView mTvActionErrorTile;

    /**
     * 今日U币
     */
    @BindView(R.id.tv_today_umoney)
    TextView mTvTodayUmoney;
    Unbinder unbinder;

    private Context mContext;
    private View mView;
    private Timer timer;
    private TimerTask task;
    private int progress;

    private ArrayList<ActionData> mActionDatas;

    // 做相对应的动作,获得的U币个数
    private static final int[] uMoney = {0, 30, 45, 55, 60, 70, 60, 30};
    private int mType;

    @Override
    protected View inflateView(LayoutInflater inflater) {
        mView = inflater.inflate(R.layout.fragment_actioncount, null, false);
        mContext = getContext();
        unbinder = ButterKnife.bind(this, mView);
        return mView;
    }

    @Override
    protected void initView(View view) {
        mTvNext.setVisibility(View.INVISIBLE);
        mCircularSeekBar.setMaxProgress(1000);
        initLongClick();//长按结束
    }

    @Override
    protected void initData() {
        // 初始化数据
        mType = ((ActionActivity) mContext).getType();
        mActionDatas = new ArrayList<>();
    }

    @Override
    public void showLockTV() {
        mCircularSeekBar.setProgressColor(Color.parseColor("#F79444"));
        nubStop.setVisibility(View.VISIBLE);
        tvLock.setVisibility(View.GONE);
    }

    @Override
    public void showStopTV() {
        mCircularSeekBar.setProgressColor(Color.parseColor("#F79444"));
        nubStop.setVisibility(View.VISIBLE);
        tvLock.setVisibility(View.GONE);
    }

    @Override
    public void startAction() {
        mBtnStart.setVisibility(View.GONE);
        nubStop.setVisibility(View.VISIBLE);
        mTvActionCountTile.setVisibility(View.GONE);
        mTvActionCorrentTile.setVisibility(View.VISIBLE);
        mTvActionErrorTile.setVisibility(View.VISIBLE);
        mTvTodayUmoney.setText("本次运动U币");
        tvUMoney.setText("0");
        tvUMoney.setTextSize(23);

        // 清空动作数据
        mActionDatas.clear();
    }

    private int correctCount;
    private int errorCount;

    @Override
    public void onActionCount(int heartRate, int errorFlag, int errorType) {
        setHeartRate(heartRate);

        if (errorFlag == 1) {
            // 正确的动作
            correctCount++;
            // 计数用的
            tvCurrentNub.setText(correctCount + "");
            // 设置U币
            tvUMoney.setText((correctCount * uMoney[mType]) + "");
        } else if (errorFlag == 2) {
            errorCount++;
            // 错误的动作
        } else if (errorFlag == 0) {
            return;
        }

        ActionData data = new ActionData();
        data.setActionType(mType);

        data.setErrorFlag(errorFlag);
        data.setErrorType(((ActionActivity) mContext).getErrorType(errorType));
        data.setErrorInfo(((ActionActivity) mContext).getErrorInfo(errorType));
        data.setErrorVideo(((ActionActivity) mContext).getErrorVideo(errorType));
        mActionDatas.add(data);

        float i = correctCount + errorCount;
        int correctPercentage = (int) ((correctCount / i) * 100);

        // 设置progressbar
        mProgressBar.setProgress(correctPercentage);
        // 设置二级
        mProgressBar.setSecondaryProgress(100);
        mProgressBar.setBackgroundColor(0x00000000);
        // 设置文字

        mTvActionCorrentTile.setText(correctPercentage + "%");
        mTvActionErrorTile.setText((100 - correctPercentage) + "%");
    }

    private void setHeartRate(int heartRate) {
        // 心率
        if (Integer.parseInt(MyApplication.mLogInDataBean.getIsalarm()) == 1) {
            if (heartRate >= Integer.parseInt(MyApplication.mLogInDataBean.getHr_alarm())) {
                tvHeartRate.startAnimation(AnimationUtils.loadAnimation(mContext, R.anim.anim_alpha));
                tvHeartRate.setTextColor(UIUtils.getColor(R.color.barrey_20));
            } else {
                tvHeartRate.clearAnimation();
                tvHeartRate.setTextColor(UIUtils.getColor(R.color.black));
            }
        }

        // 设置心率
        tvHeartRate.setText(heartRate + "");
        tvHeartRate.setTextSize(23);
    }

    @Override
    public View getLockView() {
        return tvLock;
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }


    private void initLongClick() {
        nubStop.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        nubStopPressed(R.drawable.shape_yellow_cbg, getResources().getColor(R.color.white));
                        startCount();
                        break;
                    case MotionEvent.ACTION_UP:
                        if (progress >= 1000) {
                            setCircularSeekBarProgress(progress);
                            ((ActionActivity) mContext).toFinish(0);
                        } else {
                            nubStopPressed(R.drawable.shape_cbg, getResources().getColor(R.color.progrss_bg));
                        }

                        task.cancel();
                        progress = 0;
                        setCircularSeekBarProgress(0);
                        break;
                    default:
                        break;
                }
                return true;
            }
        });
    }

    private void nubStopPressed(int shape_yellow_cbg, int color) {
        nubStop.setBackgroundResource(shape_yellow_cbg);
        nubStop.setTextColor(color);
    }

    private void startCount() {
        timer = new Timer();
        task = new TimerTask() {
            @Override
            public void run() {
                // 需要做的事:发送消息
                progress += 10;
                handler.sendEmptyMessage(1);
            }
        };
        timer.schedule(task, 0, 10);
    }

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    if (progress > 1000) {
                        task.cancel();
                    } else {
                        setCircularSeekBarProgress(progress);
                    }
            }
        }
    };


    private void setCircularSeekBarProgress(int progress) {
        mCircularSeekBar.setProgress(progress);
        mCircularSeekBar.invalidate();
    }

    @OnClick({R.id.btn_start, R.id.nub_stop, tv_action_details})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_start:

                if (!MyApplication.getApplication().isConnected) {
                    Toast.makeText(mContext, "当前未连接设备", Toast.LENGTH_SHORT).show();
                } else {
                    ActivitySwitcher.goCountTimeAct(getActivity(), mBtnStart);
                }

                break;
            case R.id.nub_stop:
                // 停止
                break;
            case R.id.tv_action_details:
                ActivitySwitcher.gotoCountActionDetails(getActivity(), mActionDatas);
                break;
            default:
                break;
        }
    }
}
